package com.franklions.casdoor.example.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.franklions.casdoor.example.context.SecurityContextHolder;
import com.franklions.casdoor.example.domain.request.SignLoginRequest;
import com.franklions.casdoor.example.exception.ErrorCode;
import com.franklions.casdoor.example.exception.ServiceException;
import io.swagger.annotations.Api;
import org.casbin.casdoor.config.CasdoorConfiguration;
import org.casbin.casdoor.entity.Session;
import org.casbin.casdoor.entity.User;
import org.casbin.casdoor.exception.AuthException;
import org.casbin.casdoor.service.AuthService;
import org.casbin.casdoor.service.SessionService;
import org.casbin.casdoor.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.annotation.Resources;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author flsh
 * @version 1.0
 * @date 2024/5/13
 * @since Jdk 1.8
 */
@Api(tags = "用户登录模块")
@RestController
public class LoginController {

    @Resource
    private AuthService casdoorAuthService;

    @Autowired
    private SessionService sessionService;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private CasdoorConfiguration configuration;

    @GetMapping("/currentUser")
    public ResponseEntity<?> currentUser() throws IOException {
        User user = SecurityContextHolder.get("userInfo",User.class);
        System.out.println(objectMapper.writeValueAsString(user));
        Session session = sessionService.getSession(user.name, configuration.getApplicationName());
        if(session!=null){
            System.out.println("session>>>>"+session.name+session.createdTime);
        }
        String resp = "{\"id\":1,\"appid\":\"123123123\",\"corporationid\":1,\"employeeid\":1,\"isAdmin\":true,\"realname\":\"管理员\",\"uid\":\"000000001\",\"name\":\"Serati Ma\",\"avatar\":\"https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png\",\"userid\":\"00000001\",\"email\":\"antdesign@alipay.com\",\"signature\":\"海纳百川，有容乃大\",\"title\":\"交互专家\",\"group\":\"蚂蚁金服－某某某事业群－某某平台部－某某技术部－UED\",\"tags\":[{\"key\":\"0\",\"label\":\"很有想法的\"},{\"key\":\"1\",\"label\":\"专注设计\"}],\"notifyCount\":12,\"unreadCount\":11,\"country\":\"China\",\"geographic\":{\"province\":{\"label\":\"浙江省\",\"key\":\"330000\"},\"city\":{\"label\":\"杭州市\",\"key\":\"330100\"}},\"address\":\"西湖区工专路 77 号\",\"phone\":\"0752-268888888\"}";
        return ResponseEntity.ok(resp);
    }

    @PostMapping("/signin/login")
    public String signInLogin(@RequestBody SignLoginRequest request){
        try {
            String oAuthToken = casdoorAuthService.getOAuthToken(request.getCode(), request.getState());
            return oAuthToken;
        }catch (AuthException ae){
            throw  new ServiceException(ErrorCode.USER_UNAUTHORIZED);
        }
    }

    @PostMapping("/signin/logout")
    public boolean signInLogin(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            User user = SecurityContextHolder.get("userInfo",User.class);
            System.out.println(objectMapper.writeValueAsString(user));
            Session session = sessionService.getSession(user.name, configuration.getApplicationName());
            if(session!=null){
                System.out.println("session>>>>"+session.name+session.createdTime);
                sessionService.deleteSession(session);
            }
            HttpSession session1 = request.getSession(false);
            if(session1 !=null){
                session1.invalidate();
            }

            return true;
        }catch (AuthException ae){
            throw  new ServiceException(ErrorCode.USER_UNAUTHORIZED);
        }
    }
}
